if (files.cwd().endsWith("脚本")) {
  let _require = require;
  require = function (path) {
    if (path.startsWith("./")) {
      path = path.replace("./", "");
    }
    path = files.cwd() + "/gdt_hb/" + path;
    return _require(path);
  }
}

auto.waitFor();
var utils = require("./utils.js");

var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!")
    while (true) {
      var allow = text("允许").findOne(5000)
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!")
        allow.click()
        sleep(1000)
        thread.interrupt()
        break
      }
    }
  })
  sleep(1000)
  var result = launchApp(app_name)
  sleep(8000)
  thread.interrupt()
  return result
}

function task() {
  var notice = id('positiveButton').findOne(10000);
  if(notice){
    notice.click();
  }
  utils.updateAppProgress(20);
  var 首页 = text('首页').findOne(20000)
  if (首页) {
    sleep(time)
    var arr = id('tv_beans_num').findOne(5000)
    if (arr) {
      var nums = parseFloat(arr.text().slice(7, 13))
      log("nums:" + nums)
      utils.updateAppProgress(60);
      if (nums > 0) {
        toastLog('已经完成充电')
        sleep(time)
      } else {
        var 一键省电 = id('btn_power_saving1').findOne(5000)
        if (一键省电) {
          一键省电.click()
          utils.updateAppProgress(80);
          sleep(random(650000,660000))
        }
      }
    }
  }
 
}

function main() {
  let open_app = launchAppEnhance("趣充");
  if (open_app) {
    task()
  }
  else {
    toastLog("趣充打开失败，请确认是否安装并授权打开!");
  }
}

try {
  main();
  utils.updateAppProgress(100);
} catch (error) {
  toastLog(error);
}

storage.put("script_running_status", "end");
